import {Component, OnInit} from '@angular/core';
import {TpStorageService} from '../../service/tp-storage.service';
import {UserService} from '../../service/user.service';
import {User} from '../../entity/user';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
    selector: 'app-oauth',
    templateUrl: './oauth.component.html',
    styleUrls: ['./oauth.component.css']
})
export class OauthComponent implements OnInit {
    constructor(private tpStorageService: TpStorageService,
                protected router: Router,
                private activatedRoute: ActivatedRoute,
                private userService: UserService) {
    }

    ngOnInit() {
        const token = this.activatedRoute.snapshot.paramMap.get('token');
        if (token) {
            this.tpStorageService.set(TpStorageService.KEY_TP_DOC_TOKEN, token);
            this.userService.loadUserByToken();
        }

        this.userService.userObservable.subscribe((user: User) => {
            if (user && user.name) {
                let url = this.tpStorageService.get(TpStorageService.KEY_URL);
                if (url) {
                    this.tpStorageService.delete(TpStorageService.KEY_URL);
                } else {
                    url = '/';
                }
                this.router.navigateByUrl(url);
            }
        });
    }
}
